package inbound_invoice

import (
	"context"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type InboundInvoiceSummarylistLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewInboundInvoiceSummarylistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InboundInvoiceSummarylistLogic {
	return &InboundInvoiceSummarylistLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InboundInvoiceSummarylistLogic) InboundInvoiceSummarylist(req *types.InboundInvoiceSummaryListRequest) (resp *types.InboundInvoiceSummaryListResponse, err error) {
	resp = new(types.InboundInvoiceSummaryListResponse)

	//1.统计供货商数量
	var total int64
	query := "SELECT count(DISTINCT supplier_id) FROM stock_in "
	tx := l.svcCtx.DB.WithContext(l.ctx).Raw(query).Scan(&total)
	switch err {
	case nil:
	case gorm.ErrEmptySlice:
		resp.Code = http.StatusNoContent
		resp.Msg = "成功"
		return resp, nil
	default:
		fmt.Printf("[Error]查询供货商数量:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}
	resp.Data.Total = total

	//2.分页
	query = "SELECT supplier_id, supplier_name, SUM(total) as total FROM stock_in where has_tax = 1 GROUP BY supplier_id,supplier_name ORDER BY total desc limit %d,%d"
	query = fmt.Sprintf(query, (req.Page-1)*req.Size, req.Size)
	var suppliers []types.StockInSupplier
	tx = l.svcCtx.DB.WithContext(l.ctx).Raw(query).Scan(&suppliers)
	switch tx.Error {
	case nil:
	case gorm.ErrEmptySlice:
		resp.Code = http.StatusNoContent
		resp.Msg = "成功"
		return resp, nil
	default:
		fmt.Printf("[Error]查询供货商分页:%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//3.统计供货商发票信息
	for _, item := range suppliers {
		var stockins []model.StockIn
		stockins, err = l.svcCtx.StockInModel.FindByPage(l.ctx, fmt.Sprintf(" where supplier_id=%d and has_tax=1", item.SupplierId))
		switch err {
		case nil:
		case model.ErrNotFound:
		default:
			fmt.Printf("[Error]查询供货商[%d]发票:%s\n", item.SupplierId, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}

		var summary = types.InboundInvoiceSummary{}
		summary.SupplierId = item.SupplierId
		summary.SupplierName = item.SupplierName

		for _, one := range stockins {
			summary.Total += one.Total
			summary.TotalTax += one.Total / 100.0 * float64(one.Tax)
		}

		//3.统计已开票信息
		var invoices []model.InboundInvoice
		invoices, err = l.svcCtx.InboundInvoiceModel.FindByPage(l.ctx, fmt.Sprintf(" where supplier_id=%d", item.SupplierId))
		switch err {
		case nil:
		case model.ErrNotFound:
		default:
			fmt.Printf("[Error]查询供货商[%d]已开发票:%s\n", item.SupplierId, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}

		for _, one := range invoices {
			summary.Used += one.Total
			summary.UsedTax += one.Total / 100.0 * float64(one.Tax)
		}

		summary.Available = summary.Total - summary.Used
		summary.AvailableTax = summary.TotalTax - summary.UsedTax

		resp.Data.List = append(resp.Data.List, summary)
	}

	sj, _ := json.Marshal(&resp.Data)
	fmt.Printf("发票汇总列表：%s\n", string(sj))

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
